package com.antdant.service;

import cn.hutool.http.useragent.UserAgent;
import cn.hutool.http.useragent.UserAgentUtil;
import com.antdant.constant.LoginOperationTypeEnum;
import com.antdant.entity.UserLoginLog;
import com.antdant.repository.UserLoginLogRepository;
import com.antdant.model.UserLoginVo;
import com.antdant.utils.DateUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;

/**
 * @Author Lee Yunc
 * @Date 2021/2/24 9:57
 * @Description:
 * @Version 1.0
 */
@Service
public class UserLoginLogService {

    @Autowired
    private UserLoginLogRepository userLoginLogRepository;

    /**
     * 添加登入记录
     *
     * @param ip
     * @param userLoginVo
     * @param userAgent
     * @return
     */
    @Transactional(rollbackFor = Exception.class)
    public UserLoginLog addLoginLog(String ip, UserLoginVo userLoginVo, String userAgent) {
        UserLoginLog userLoginLog = new UserLoginLog();
        userLoginLog.setCreateTime(DateUtils.getNowTime());
        userLoginLog.setIp(ip);
        userLoginLog.setUserLoginId(userLoginVo.getUser().getLoginId());
        userLoginLog.setUserAgent(userAgent);
        userLoginLog.setOperationType(LoginOperationTypeEnum.LOGIN.getOperationType());
        UserAgent userAgentInfo = UserAgentUtil.parse(userAgent);
        userLoginLog.setOperatingSystemVersion(userAgentInfo.getOs().getName());
        userLoginLog.setBrowserVersion(userAgentInfo.getBrowser().getName());
        userLoginLog.setUserToken(userLoginVo.getUserToken());
        userLoginLogRepository.save(userLoginLog);
        return userLoginLog;
    }

    /**
     * 添加登出记录
     *
     * @param ip
     * @param userLoginVo
     * @param userAgent
     * @return
     */
    @Transactional(rollbackFor = Exception.class)
    public UserLoginLog addLogoutLog(String ip, UserLoginVo userLoginVo, String userAgent) {
        UserLoginLog userLoginLog = new UserLoginLog();
        userLoginLog.setCreateTime(DateUtils.getNowTime());
        userLoginLog.setIp(ip);
        userLoginLog.setUserLoginId(userLoginVo.getUser().getLoginId());
        userLoginLog.setUserAgent(userAgent);
        userLoginLog.setOperationType(LoginOperationTypeEnum.LOGOUT.getOperationType());
        UserAgent userAgentInfo = UserAgentUtil.parse(userAgent);
        userLoginLog.setOperatingSystemVersion(userAgentInfo.getOs().getName());
        userLoginLog.setBrowserVersion(userAgentInfo.getBrowser().getName());
        userLoginLogRepository.save(userLoginLog);
        return userLoginLog;
    }

    /**
     * 通过登录id删除用户
     *
     * @param userLoginId
     * @return
     */
    public boolean deleteByUserLoginId(String userLoginId) {
        return userLoginLogRepository.deleteByUserLoginId(userLoginId);
    }
}
